package com.qk.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.entity.OperateLog;
import com.qk.mapper.OperateLogMapper;
import com.qk.service.OperateLogService;
import com.qk.util.CurrentUserContextHolders;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author: zhangchuang
 * @Date: 2025/10/17 20:32
 * @Description: 日志切面
 */
@Aspect
@Slf4j
@Component
@Order(10)
@SuppressWarnings("all")
public class LogRecordAOP {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.qk.aop.anno.LogRecord)")
    public Object aroundLog(ProceedingJoinPoint pjp) {
        Object res = null;
        try {
            long s = 0;
            try {
                log.info("日志切面开始执行");
                s = System.currentTimeMillis();
            } catch (Exception e) {
            }
            res = pjp.proceed();
            long e = System.currentTimeMillis();
            try {
                operateLogMapper.insert(OperateLog.builder()
                        .operateUserId(CurrentUserContextHolders.getId())
                        .operateTime(LocalDateTime.now())
                        .methodName(pjp.getSignature().getName())
                        .className(pjp.getTarget().getClass().getName())
                        .methodParams(JSONUtil.toJsonStr(pjp.getArgs()))
                        .returnValue(JSONUtil.toJsonStr(res))
                        .costTime(e - s)
                        .build());
            } catch (Exception ex) {
                log.error("操作日志插入数据库异常: {}", ex.getMessage());
            }
        } catch (Throwable e) {
            res = Result.error("业务操作执行异常");
            log.error("日志切面执行异常,{}", e.getMessage());
        }
        return res;
    }
}
